package com.zhangmeng.tools.json2Pojo;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.sun.codemodel.JCodeModel;
import lombok.SneakyThrows;
import org.jsonschema2pojo.SchemaMapper;
import org.springframework.util.Assert;

import java.io.ByteArrayOutputStream;

/**
 * @author : 芊芊墨客
 * @version : 1.0
 * @date : 2023-04-21 09:22
 *  * 源代码链接地址: https://blog.csdn.net/weixin_39651356/article/details/127155659
 */
public class Json2PojoCodeGeneratorUtil{

    @SneakyThrows
    public static String json2pojo(String jsonContent) {
        return json2pojo(jsonContent, "TestBean", ClassUtil.getPackage(Json2PojoCodeGeneratorUtil.class),
                AnnotateConfig.builder()
                        .mybatis_plus_enable(true)
                        .swagger_enable(true)
                        .lombook_enable(true)
                        .jackson_enable(true)
                        .build()
                );
    }

    /**
     * json内容转成Bean代码
     * @param jsonContent json内容
     * @param pojoClassName 生成的Bean的Class名字
     * @param pojoPackageName 生成的Bean的包名字
     * @return
     */
    @SneakyThrows
    public static String json2pojo(String jsonContent, String pojoClassName, String pojoPackageName,AnnotateConfig annotateConfig) {
        return json2pojo(Json2PojoCodeGeneratorConfig.builder()
                .jsonContent(jsonContent)
                .pojoClassName(pojoClassName)
                .pojoPackageName(pojoPackageName)
                .build(),annotateConfig);
    }



    /**
     * json内容转成Bean代码
     * @param json2PojoGenerateConfig 配置信息
     * @return
     */
    @SneakyThrows
    public static String json2pojo(Json2PojoCodeGeneratorConfig json2PojoGenerateConfig,AnnotateConfig annotateConfig) {
        String jsonContent = json2PojoGenerateConfig.getJsonContent();
        Assert.isTrue(JSONUtil.isTypeJSON(jsonContent), "非JSON内容，请检查");
        String pojoClassName = StrUtil.blankToDefault(json2PojoGenerateConfig.getPojoClassName(), "TestBean");
        String pojoPackageName = StrUtil.blankToDefault(json2PojoGenerateConfig.getPojoPackageName(), ClassUtil.getPackage(Json2PojoCodeGeneratorUtil.class));

        //1. 生成配置设置
        SchemaMapper mapper = MyJsonschema2pojoConfig.getDefaultSchemaMapper(annotateConfig);
        JCodeModel codeModel = new JCodeModel();
        mapper.generate(codeModel, pojoClassName, pojoPackageName, jsonContent);

        //2. 开始生成代码
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        MyCodeWriter myCodeWriter = new MyCodeWriter(byteArrayOutputStream);
        codeModel.build(myCodeWriter);

        //3. 获取结果
        String result = new String(byteArrayOutputStream.toByteArray());

        return StrUtil.trim(result);
    }

    public String generate(Json2PojoCodeGeneratorConfig generatorConfig,AnnotateConfig annotateConfig) {
        return json2pojo(generatorConfig,annotateConfig);
    }
}
